import 'package:flutter/material.dart';

// 关闭消息的函数类型
typedef CloseMessageFunc = void Function();

// 消息类型枚举
enum MessageType { error, success, warning, info, loading }

class MessageUtil {
  // 单例模式
  static final MessageUtil _instance = MessageUtil._internal();
  static GlobalKey<NavigatorState>? _navigatorKey;

  // 获取当前有效的context
  static BuildContext? get _safeContext {
    if (_navigatorKey?.currentContext != null && _navigatorKey!.currentState?.mounted == true) {
      return _navigatorKey!.currentContext;
    }
    return null;
  }

  // 使用OverlayEntry管理消息
  OverlayEntry? _messageOverlayEntry;
  bool _isMessageShowing = false;

  factory MessageUtil() => _instance;
  MessageUtil._internal();

  // 私有方法：隐藏消息
  void _hideMessage() {
    if (_isMessageShowing && _messageOverlayEntry != null) {
      try {
        _messageOverlayEntry?.remove();
      } catch (e) {
        debugPrint('Error hiding message: $e');
      } finally {
        _isMessageShowing = false;
        _messageOverlayEntry = null;
      }
    }
  }

  // 核心方法：显示消息（支持toast和loading）
  CloseMessageFunc _showMessage({
    String? message,
    required MessageType type,
    int dismissAfterSeconds = -1, // -1表示使用默认值
    bool showLoading = false,
  }) {
    final context = _safeContext;
    if (context == null) return () {};

    if (_isMessageShowing) _hideMessage();

    // 设置默认消失时间
    final dismissTime =
        dismissAfterSeconds >= 0
            ? dismissAfterSeconds
            : showLoading
            ? 0
            : 3;

    final overlayState = Overlay.of(context);
    _messageOverlayEntry = OverlayEntry(
      builder: (context) {
        final theme = Theme.of(context);
        final colorScheme = theme.colorScheme;
        final isDark = theme.brightness == Brightness.dark;

        // 根据类型确定样式
        late final IconData icon;
        late final Color backgroundColor;
        late final Color textColor;

        switch (type) {
          case MessageType.error:
            icon = Icons.error_outline;
            backgroundColor = colorScheme.error;
            textColor = colorScheme.onError;
            break;
          case MessageType.success:
            icon = Icons.check_circle_outline;
            backgroundColor = colorScheme.primary;
            textColor = colorScheme.onPrimary;
            break;
          case MessageType.warning:
            icon = Icons.warning_amber_outlined;
            backgroundColor = const Color(0xFFE6A23C);
            textColor = colorScheme.onPrimary;
            break;
          case MessageType.info:
          case MessageType.loading:
            icon = Icons.info_outline;
            backgroundColor = isDark ? Colors.grey[800]! : Colors.grey[700]!;
            textColor = Colors.white;
            break;
        }

        return Stack(
          children: [
            // 如果是loading类型，添加遮罩
            if (showLoading) ModalBarrier(color: Colors.black.withOpacity(0.4), dismissible: false),
            // 消息内容
            showLoading
                ? Center(
                  child: Container(
                    padding: const EdgeInsets.all(24),
                    decoration: BoxDecoration(
                      color: backgroundColor,
                      borderRadius: BorderRadius.circular(16),
                      boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.1), blurRadius: 12)],
                    ),
                    constraints: const BoxConstraints(minWidth: 200, maxWidth: 300),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        type == MessageType.loading
                            ? CircularProgressIndicator(color: textColor, strokeWidth: 3)
                            : Icon(icon, size: 24, color: textColor),
                        const SizedBox(height: 20),
                        Text(
                          message ?? 'Loading...',
                          style: theme.textTheme.bodyMedium?.copyWith(color: textColor),
                          textAlign: TextAlign.center,
                        ),
                      ],
                    ),
                  ),
                )
                : Center(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 20),
                    child: Material(
                      color: Colors.transparent,
                      child: Container(
                        constraints: const BoxConstraints(maxWidth: 600),
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                        decoration: BoxDecoration(
                          color: backgroundColor,
                          borderRadius: BorderRadius.circular(8),
                          boxShadow: [
                            BoxShadow(color: Colors.black.withOpacity(0.2), blurRadius: 8, offset: const Offset(0, 4)),
                          ],
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(icon, size: 24, color: textColor),
                            const SizedBox(width: 8),
                            Flexible(
                              child: Text(
                                message ?? '',
                                style: TextStyle(color: textColor),
                                maxLines: 3,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
          ],
        );
      },
    );

    overlayState.insert(_messageOverlayEntry!);
    _isMessageShowing = true;

    // 自动关闭逻辑
    if (dismissTime > 0) {
      Future.delayed(Duration(seconds: dismissTime), _hideMessage);
    }

    return _hideMessage;
  }

  // 快捷消息方法
  static void error(String message) => _showSnackBar(message, MessageType.error);

  static void info(String message) => _showSnackBar(message, MessageType.info);

  // 初始化方法
  static void init(GlobalKey<NavigatorState> navigatorKey) {
    _navigatorKey = navigatorKey;
  }

  // Loading样式消息
  static CloseMessageFunc loading(String message, {int dismissAfterSeconds = 0}) {
    return _instance._showMessage(
      message: message,
      type: MessageType.loading,
      dismissAfterSeconds: dismissAfterSeconds,
      showLoading: true,
    );
  }

  // 确认对话框
  static Future<bool?> showConfirmDialog({
    required String title,
    required String message,
    String confirmText = 'Confirm',
    String cancelText = 'Cancel',
    Color confirmColor = Colors.red,
    VoidCallback? onConfirm,
    VoidCallback? onCancel,
  }) async {
    final context = _safeContext;
    if (context == null) return null;

    return await showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text(title),
          content: Text(message),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(false);
                onCancel?.call();
              },
              child: Text(cancelText),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(true);
                onConfirm?.call();
              },
              style: TextButton.styleFrom(foregroundColor: confirmColor),
              child: Text(confirmText),
            ),
          ],
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        );
      },
    );
  }

  static void success(String message) => _showSnackBar(message, MessageType.success);
  /* ========== 公共API方法 ========== */

  // Toast样式消息
  static CloseMessageFunc toast(String message, {int dismissAfterSeconds = 3}) {
    return _instance._showMessage(
      message: message,
      type: MessageType.info,
      dismissAfterSeconds: dismissAfterSeconds,
      showLoading: false,
    );
  }

  static void warning(String message) => _showSnackBar(message, MessageType.warning);

  // 私有方法：显示SnackBar
  static void _showSnackBar(String message, MessageType type) {
    final context = _safeContext;
    if (context == null) return;

    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;

    late final Color backgroundColor;
    late final Color textColor;
    late final IconData icon;

    switch (type) {
      case MessageType.error:
        backgroundColor = colorScheme.error;
        textColor = colorScheme.onError;
        icon = Icons.error_outline;
        break;
      case MessageType.success:
        backgroundColor = colorScheme.primary;
        textColor = colorScheme.onPrimary;
        icon = Icons.check_circle_outline;
        break;
      case MessageType.warning:
        backgroundColor = const Color(0xFFE6A23C);
        textColor = colorScheme.onPrimary;
        icon = Icons.warning_amber_outlined;
        break;
      case MessageType.info:
      case MessageType.loading:
        backgroundColor = colorScheme.surface;
        textColor = colorScheme.onSurface;
        icon = Icons.info_outline;
        break;
    }

    final content = Row(
      children: [
        Icon(icon, size: 24, color: textColor),
        const SizedBox(width: 8),
        Flexible(
          child: Text(message, style: TextStyle(color: textColor), maxLines: 3, overflow: TextOverflow.ellipsis),
        ),
      ],
    );

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: content,
        behavior: SnackBarBehavior.floating,
        backgroundColor: backgroundColor,
        duration: const Duration(seconds: 4),
        margin: const EdgeInsets.all(20),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      ),
    );
  }
}


// MessageUtil.success('MessageUtil.success');
// MessageUtil.info('MessageUtil.info');
// MessageUtil.warning('MessageUtil.warning');
// MessageUtil.error('MessageUtil.error');
// MessageUtil.toast('MessageUtil.toast');
// // dismissAfterSeconds 消失时间，若为0，表示不消失
// final closeToast = MessageUtil.toast(data['message'] ?? 'Login failed', dismissAfterSeconds: 0);
// Future.delayed(const Duration(seconds: 10), closeToast);
// final confirmed = await MessageUtil.showConfirmDialog(
//   title: ('confirm_logout_title'),
//   message: ('confirm_logout_message'),
//   confirmText: ('log_out'),
//   cancelText: ('cancel'),
//   onConfirm: () {
//     // MessageUtil.loading('加载中...', dismissAfterSeconds: 3);
//     final closeLoading = MessageUtil.loading('加载中...');
//     Future.delayed(const Duration(seconds: 5), closeLoading);
//   },
// );
// debugPrint('confirmed $confirmed');